﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Runtime.InteropServices;

namespace RedFoxUtils
{
  public sealed class Helper
  {
    [DllImport("wininet.dll", SetLastError = true)]
    public static extern bool InternetGetCookieEx(
        string url,
        string cookieName,
        StringBuilder cookieData,
        ref int size,
        Int32 dwFlags,
        IntPtr lpReserved);

    private const Int32 InternetCookieHttponly = 0x2000;

    /// <summary>
    /// Gets the URI cookie container.
    /// </summary>
    /// <param name="uri">The URI.</param>
    /// <returns></returns>
    public static CookieContainer GetUriCookieContainer(Uri uri)
    {
      CookieContainer cookies = null;
      // Determine the size of the cookie
      int datasize = 8192 * 16;
      StringBuilder cookieData = new StringBuilder(datasize);
      if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
      {
        if (datasize < 0)
          return null;
        // Allocate stringbuilder large enough to hold the cookie
        cookieData = new StringBuilder(datasize);
        if (!InternetGetCookieEx(
            uri.ToString(),
            null, cookieData,
            ref datasize,
            InternetCookieHttponly,
            IntPtr.Zero))
          return null;
      }
      if (cookieData.Length > 0)
      {
        cookies = new CookieContainer();
        cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
      }
      return cookies;
    }

    /// <summary>
    /// Encode the specified orig string to big5.
    /// </summary>
    /// <param name="origString">The orig string.</param>
    /// <returns></returns>
    public static byte[] unicode2big5bytes( string origString )
    {
      try
      {
        byte[] origBytes = Encoding.Unicode.GetBytes(origString);
        byte[] convertedBytes = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(950), origBytes);
        return convertedBytes;
      }
      catch (Exception ex)
      {
        Debug.WriteLine(ex.Message);
      }
      return null;
    }

    public static string unicode2EncodedBig5( string origString )
    {
      byte[] bytes = unicode2big5bytes(origString);
      StringBuilder sb = new StringBuilder();
      foreach (byte b in bytes)
        sb.Append("%" + b.ToString("X2"));
      return sb.ToString();
    }
  }
}
